package com.zhgxi.zf.service;

import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.slave4j.orm.Filtration;
import org.slave4j.orm.Filtration.MatchType;
import org.slave4j.orm.hibernate.BaseDao;
import org.slave4j.orm.hibernate.BaseService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhgxi.zf.entity.Menu;
import com.zhgxi.zf.util.MenuComparator;

@Service
@Transactional
public class MenuService extends BaseService<Menu> {
	@Override
	@Resource(name = "menuDao")
	public void setBaseDao(BaseDao<Menu> baseDao) {
		this.baseDao = baseDao;
	}

	public List<Menu> findByType(Boolean type) {
		Filtration filter = new Filtration(MatchType.EQ, type, "menutype");
		Filtration visible = new Filtration(MatchType.EQ, true, "visible");
		return sort(baseDao.findList(filter, visible));
	}
	
	public List<Menu> findByPid(Integer pid) {
		Filtration filter = new Filtration(MatchType.EQ, pid, "parent.id");
		Filtration visible = new Filtration(MatchType.EQ, true, "visible");
		return sort(baseDao.findList(filter, visible));
	}
	
	public boolean deleteMenu(Menu m) {
		try {
			if (m.getParent() == null) {
				List<Menu> list = findByPid(m.getId());
				for(Menu mn:list) {
					baseDao.unVisible(mn.getId());
				}
			}
			baseDao.unVisible(m.getId());
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	public List<Menu> findAllMenu() {
		Filtration visible = new Filtration(MatchType.EQ, true, "visible");
		List<Menu> list = baseDao.findList(visible);
		return sort(list);
	}
	
	public List<Menu> findByMname(String mname) {
		Filtration filter = new Filtration(MatchType.LIKE, mname, "menuname");
		Filtration visible = new Filtration(MatchType.EQ, true, "visible");
		return sort(baseDao.findList(filter,visible));
	}
	
	private List<Menu> sort(List<Menu> list) {
		MenuComparator menuCom = new MenuComparator();
		Collections.sort(list, menuCom);
		return list;
	}
	
	public boolean saveMenu(Menu menu) {
		try {
			if (menu.isNew() || menu.getId() == 0) {
				baseDao.save(menu);
			} else {
				baseDao.update(menu);
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}
